import { isUndefined } from "../utils/util";

export default {
    $setStorage(key, value, time) {
        let val = {
            data: typeof value === 'object' ? JSON.stringify(value) : value,
        };
        if (!isUndefined(time)) {
            const seconds = parseInt(time);
            if (seconds > 0) {
                const timestamp = Math.floor(Date.now() / 1000) + seconds;
                val.time = timestamp;
            }
        }
        wx.setStorageSync('__' + key, val);
    },

    $getStorage(key) {
        let getVal = wx.getStorageSync('__' + key) || wx.getStorageSync(key);
        if (isUndefined(getVal) || getVal === '') return null;

        // 判断是否有过期时间
        if (!isUndefined(getVal.time) && parseInt(getVal.time) < Date.now() / 1000) {
            wx.removeStorageSync('__' + key);
            return null;
        }

        // 尝试解析数据
        try {
            return JSON.parse(getVal.data || getVal);
        } catch (error) {
            return getVal.data || getVal;
        }
    },

    $removeStorage(key) {
        wx.removeStorageSync('__' + key);
    },

    $clearStorage() {
        wx.clearStorageSync();
    }
};
